<template>
  <!-- action的值可以为空，但必须存在  -->
  <el-upload
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="handleChange"
  >
    <img v-if="props.avatar" :src="uploadAvatar" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script setup>
import { useStore } from "vuex";
import { Plus } from "@element-plus/icons-vue";
import { computed } from "vue";

const store = useStore();

const props = defineProps({
  avatar: String,
});

const emit = defineEmits(["imgChange"]);

const uploadAvatar = computed(() =>
  props.avatar.includes("blob")
    ? props.avatar
    : store.state.API_BASE_URL + props.avatar
);

// 选择完图片的信息返回给父组件调用
const handleChange = (file) => {
  emit("imgChange", file.raw);
};
</script>

<style lang="scss" scoped>
:deep() {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
